import { Placement } from "../shared/reactFlags";
import { IFiber } from "./updateContainer";

export function placeChild(
  newFiber: IFiber,
  lastPlacedIndex: number,
  newIndex: number,
  shouldTrackSideEffects: boolean
): number {
  newFiber.index = newIndex;

  // 判断是否为更新阶段
  if (shouldTrackSideEffects) {
    const current = newFiber.alternate;

    if (current) {
      const oldIndex = current.index;

      // 若旧fiber的index大于了lastPlacedIndex证明进行了节点的删除或者移动操作
      if (oldIndex < lastPlacedIndex) {
        // 证明需要移动
        newFiber.flags |= Placement;
      } else {
        // 证明oldIndex需要作为新的lastPlacedIndex
        return oldIndex;
      }
    } else {
      // 证明该fiber是新创建的 fiber
      newFiber.flags |= Placement;
    }
  }

  // 第一次渲染，不需要记录，直接返回
  return lastPlacedIndex;
}

/**
 * 判断两个节点是否相等
 * @param newFiber 新的fiber
 * @param oldFiber 旧的vdom
 * @returns
 */
export function same(newFiber: IFiber, oldFiber: IFiber | null) {
  return oldFiber && oldFiber.key === newFiber.key && oldFiber.type === newFiber.type;
}

export function deleteOldFiber(parentFieber: any, childToDelete: any) {
  if (parentFieber.deletions) {
    parentFieber.deletions.push(childToDelete);
  } else {
    parentFieber.deletions = [childToDelete];
  }
}

/**
 * 将剩余的子节点标记删除
 * @param parentFieber 父Fiber
 * @param childToDelete 要删除的子fiber
 */
export function deleteRemainingChildren(parentFieber: any, childToDelete: any) {
  let node = childToDelete;
  while (node) {
    deleteOldFiber(parentFieber, node);
    node = node.sibling;
  }
}

export function mapRemainingChildren(fiber: IFiber) {
  const map = new Map();

  let node = fiber;
  while (node) {
    map.set(node.key || node.index, node);
  }

  return map;
}
